﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;
using Microsoft.Phone.Shell;
using ImageTools;
using ImageTools.IO;
using ImageTools.IO.Png;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;
using System.IO;
using Microsoft.Phone.Tasks;
using PressureDiary.ViewModels;

namespace PressureDiary
{
    public partial class MainPage : PhoneApplicationPage
    {
        private List<Measure> Measures = new List<Measure>();
        private bool isModified = false;
        //CustomTile myCustomTile;

        private int actualMonth = DateTime.Now.Month;
        //private List<Measure> measuresInMonth = new List<Measure>();
        private List<MonthViewModel> months = new List<MonthViewModel>();
        private Measure globalMeasure = new Measure();

        private AppSettings settings = new AppSettings();

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            Application.Current.Host.Settings.EnableFrameRateCounter = false;

            txtEmail.Text = settings.EmailSettings;

            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!this.isModified)
                {
                    this.Max.DataSource = new NumberSelector.NumbersDataSource() { Minimum = 60, Maximum = 300, SelectedItem = 120 };
                    this.Min.DataSource = new NumberSelector.NumbersDataSource() { Minimum = 30, Maximum = 150, SelectedItem = 80 };
                    this.HeartBeat.DataSource = new NumberSelector.NumbersDataSource() { Minimum = 40, Maximum = 90, SelectedItem = 60 };
                }
                else
                {
                    this.Max.DataSource.SelectedItem = App.values[0];
                    this.Min.DataSource.SelectedItem = App.values[1];
                    this.HeartBeat.DataSource.SelectedItem = App.values[2];
                }

                //LoadMeasurementsData();
                LoadMeasurementDataGroupedByMonth();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadMeasurementDataGroupedByMonth()
        {
            this.months.Clear();
            this.MeasurementListBox.ItemsSource = new List<MonthViewModel>();

            using (MyDatabaseContext context = new MyDatabaseContext(MyDatabaseContext.ConnectionString))
            {
                this.Measures = context.Measures.ToList();
                //this.Measures.Reverse();

                var query = this.Measures.GroupBy(x => x.Date.Value.Month).ToList();

                foreach (var item in query.AsEnumerable())
                {
                    MonthViewModel mvm = new MonthViewModel();
                    DateTime yearMonth = item.First().Date.Value;
                    mvm.Key = yearMonth.Year + "-" + yearMonth.Month.ToString("00");
                    mvm.MonthYear = yearMonth.Year + " " + yearMonth.ToString("MMMM");
                    mvm.Count = item.Count();

                    this.months.Add(mvm);
                }

                App.measuresInMonth = this.Measures.Where(x => x.Date.Value.Month == actualMonth).Count();

                MeasurementListBox.ItemsSource = this.months.OrderByDescending(x => x.Key);
            }
        }

        //private void LoadMeasurementsData()
        //{
        //    using (MyDatabaseContext context = new MyDatabaseContext(MyDatabaseContext.ConnectionString))
        //    {
        //        this.Measures = context.Measures.ToList();
        //        this.Measures.Reverse();

        //        this.measuresInMonth = this.Measures.Where(x => x.Date.Value.Month == actualMonth).ToList();

        //        MeasurementListBox.ItemsSource = this.Measures;
        //    }
        //}

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            #region CREATION MEASURE OBJECT
            Measure measure = new Measure();

            measure.Id = Guid.NewGuid();
            measure.Systolic = Convert.ToInt16(this.Max.DataSource.SelectedItem.ToString());
            measure.Diastolic = Convert.ToInt16(this.Min.DataSource.SelectedItem.ToString());
            measure.Pulse = Convert.ToInt16(this.HeartBeat.DataSource.SelectedItem.ToString());
            measure.Date = datePickerMeasurementDate.Value;
            measure.TimeMeasure = timePickerMeasurementTime.Value;

            #endregion

            //this.measure = measure;

            // Save the Measure object on the database
            using (MyDatabaseContext context = new MyDatabaseContext(MyDatabaseContext.ConnectionString))
            {
                context.Measures.InsertOnSubmit(measure);
                context.SubmitChanges();
            }

            MessageBox.Show("Data was successfully saved!");

            this.isModified = false;
            //LoadMeasurementsData();
            LoadMeasurementDataGroupedByMonth();

            this.globalMeasure = measure;

            //BuildLiveTile();
            //PinLiveTile();
            //CreateLiveTile();
            //CreateTile();
            //BuildTile(); // Funziona ma esco subito dall'applicazione

            CreateApplicationTile();
        }


        public void CreateApplicationTile()
        {
            var appTile = ShellTile.ActiveTiles.First();

            if (appTile != null)
            {
                var standardTile = new StandardTileData
                {
                    Title = App.ApplicationName,
                    BackgroundImage = new Uri("Images/PressureDiaryIcon_173x173.png", UriKind.Relative),
                    Count = App.measuresInMonth, // ci metto il numero di misurazioni del mese in corso
                    BackTitle = App.ApplicationName,
                    //BackBackgroundImage = new Uri("Images/ApplicationTileIcon.jpg", UriKind.Relative),  
                    BackContent = "Last measure: " + "[" + this.globalMeasure.Systolic.ToString() + "/" + this.globalMeasure.Diastolic.ToString() + "]" + this.globalMeasure.Date.Value.ToShortDateString()
                };

                appTile.Update(standardTile);
            }
        }

        #region LIveTiles
        private void BuildTile()
        {
            var bmp = new WriteableBitmap(173, 173);

            var logo = new BitmapImage(new Uri("/Images/PressureDiaryIcon_173x173.png", UriKind.Relative));
            var img = new Image { Source = logo };

            logo.CreateOptions = BitmapCreateOptions.None;

            var bl = new TextBlock();
            bl.Foreground = new SolidColorBrush(Colors.White);
            bl.FontSize = 24.0;
            bl.Text = App.ApplicationName;

            bmp.Render(bl, null);

            var tt = new TranslateTransform();
            tt.X = 173 - logo.PixelWidth;
            tt.Y = 173 - logo.PixelHeight;

            bmp.Render(img, tt);

            bmp.Invalidate();

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                var filename = "/Shared/ShellContent/PressureDiary.jpg";
                using (var st = new IsolatedStorageFileStream(filename, FileMode.Create, FileAccess.Write, store))
                {
                    bmp.SaveJpeg(st, 173, 173, 0, 100);
                }
            }

            var tile = new StandardTileData();

            tile.BackgroundImage = new Uri("isostore:/Shared/ShellContent/PressureDiary.jpg", UriKind.Absolute);
            tile.BackContent = "Last measure captured: " + this.globalMeasure.Date.Value.ToShortDateString();

            ShellTile.Create(new Uri("/MainPage.xaml?DefaultTitle=FromSecondaryTile",
                                                                        UriKind.Relative), tile);

        }

        private void CreateTile()
        {
            TileControl frontTile = new TileControl();
            TileData tileData = new TileData() { ImageSource = "Images/PressureDiaryIcon_173x173.png", Text1 = this.globalMeasure.Systolic.ToString(), Text2 = this.globalMeasure.Diastolic.ToString() };
            frontTile.DataContext = tileData;

            ShellTile primaryTile = ShellTile.ActiveTiles.First();

            StandardTileData std = frontTile.ToTile();
            std.BackContent = "Last survey: " + this.globalMeasure.Date.Value.ToShortDateString();

            if (primaryTile != null)
            {
                primaryTile.Update(std);
            }
        }

        //private void BuildLiveTile()
        //{
        //    //myCustomTile = Ree7.TileToolkit.CustomTileFactory.GetTemplatedTile("MyTile",
        //    //    new NativeCountTileTemplate()
        //    //    {
        //    //        // You can set any kind of brush as the background (Image, Gradient, SolidColor)
        //    //        // or just do not set the property to leave it transparent (and use the phone theme color)
        //    //        // You can also tweak the foreground color, which will affect text items (count, app name)
        //    //        // but to follow the WP guidelines, you'd better stick with white (default).
        //    //        Background = null,
        //    //        // For the icon you have to use a BitmapImage (from your app content, resources, from a remote url, whatever...)
        //    //        Icon = new BitmapImage()
        //    //        {
        //    //            CreateOptions = BitmapCreateOptions.None,
        //    //            UriSource = new Uri("Images/coffee-cup.png", UriKind.Relative)
        //    //        },
        //    //        // The count index displayed on the tile
        //    //        Count = "8",
        //    //        // The app name displayed on the tile
        //    //        AppName = App.ApplicationName
        //    //    },
        //    //    TileSize.Standard);

        //    myCustomTile = CustomTileFactory.GetTemplatedTile("MyTile",
        //        new NativeCountTileTemplate()
        //        {
        //            //Background = new ImageBrush()
        //            //{
        //            //    ImageSource = new BitmapImage()
        //            //    {
        //            //        CreateOptions = BitmapCreateOptions.None,
        //            //        UriSource = new Uri("Images/PressureDiaryIcon_173x173.png", UriKind.Relative)
        //            //    }
        //            //},
        //            Background = null,
        //            Icon = new BitmapImage()
        //            {
        //                CreateOptions = BitmapCreateOptions.None,
        //                UriSource = new Uri("Images/PressureDiaryIcon_173x173.png", UriKind.Relative)
        //            },
        //            Count = "2",
        //            AppName = App.ApplicationName
        //        },
        //        TileSize.Standard);
        //}

        //private void PinLiveTile()
        //{
        //    // Remove the tile if it already exists or the creation will miserably fail
        //    ShellTile existingTile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("MyTile"));
        //    if (existingTile != null) existingTile.Delete();

        //    // Example of further customization of the Standard page data
        //    StandardTileData std = myCustomTile.GetShellTileData();           
        //    std.BackContent = "Last survey: " + this.globalMeasure.Date.Value.ToShortDateString();

        //    ShellTile.Create(new Uri("/MainPage.xaml?src=MyTile", UriKind.Relative), std);
        //}

        private void CreateLiveTile()
        {
            var mySweetDynamicTile = new DynamicTile
            {
                Text = this.globalMeasure.Systolic.ToString() + "/" + this.globalMeasure.Diastolic.ToString(),
                Title = App.ApplicationName,
                //Background = new SolidColorBrush(Colors.Purple),
                Background = new ImageBrush()
                {
                    ImageSource = new BitmapImage()
                    {
                        CreateOptions = BitmapCreateOptions.None,
                        UriSource = new Uri("Images/PressureDiaryIcon_173x173.png", UriKind.Relative)
                    }
                }

            };

            // Retrieve the contents of the tile as a StandardTileData
            var newTile = new StandardTileData();
            try
            {
                newTile = mySweetDynamicTile.ToTile();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


            // Use the new tile as the primary tile for this app.
            ShellTile primaryTile = ShellTile.ActiveTiles.First();
            newTile.BackContent = "Last survey: " + this.globalMeasure.Date.Value.ToShortDateString();

            if (primaryTile != null)
            {
                primaryTile.Update(newTile);
            }
        }
        #endregion

        //private void DeleteItem_Click(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        var menuItemGuid = ((MenuItem)sender).CommandParameter;


        //        if (MessageBox.Show("Do you really wanna delete this measure?", "Warning", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
        //        {
        //            using (MyDatabaseContext context = new MyDatabaseContext(MyDatabaseContext.ConnectionString))
        //            {
        //                Measure measure = context.Measures.Where(x => x.Id.ToString() == menuItemGuid).SingleOrDefault();
        //                context.Measures.DeleteOnSubmit(measure);
        //                context.SubmitChanges();
        //            }
        //        }
        //        LoadMeasurementsData();
        //    }
        //    catch (Exception)
        //    {
        //        MessageBox.Show("Error deleting item.", "ERROR", MessageBoxButton.OK);
        //    }
        //}

        private void datePickerMeasurementDate_GotFocus(object sender, RoutedEventArgs e)
        {
            App.values[0] = Convert.ToInt16(this.Max.DataSource.SelectedItem);
            App.values[1] = Convert.ToInt16(this.Min.DataSource.SelectedItem);
            App.values[2] = Convert.ToInt16(this.HeartBeat.DataSource.SelectedItem);

            this.isModified = true;
        }

        private void timePickerMeasurementTime_GotFocus(object sender, RoutedEventArgs e)
        {
            App.values[0] = Convert.ToInt16(this.Max.DataSource.SelectedItem);
            App.values[1] = Convert.ToInt16(this.Min.DataSource.SelectedItem);
            App.values[2] = Convert.ToInt16(this.HeartBeat.DataSource.SelectedItem);

            this.isModified = true;
        }

        private void AboutMe_Click(object sender, RoutedEventArgs e)
        {
            WebBrowserTask wtb = new WebBrowserTask();
            wtb.Uri = new Uri("http://aaccostatech.wordpress.com/", UriKind.Absolute);
            wtb.Show();
        }

        private void SendEmail_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var menuItemKey = ((MenuItem)sender).CommandParameter;
                //NavigationService.Navigate(new Uri("/DetailsPage.xaml?key=" + menuItemKey.ToString(), UriKind.Relative));                

                // Sezione spedizione mail
                EmailComposeTask email = new EmailComposeTask();
                if (settings.EmailSettings != string.Empty)
                {
                    email.To = settings.EmailSettings;
                    email.Subject = "Measures " + menuItemKey.ToString();
                    email.Body = Utility.getBody(menuItemKey.ToString());
                    email.Show();
                }
                else
                {
                    MessageBox.Show("Configure email address in settings page.", "WARNING", MessageBoxButton.OK);
                }
                
            }
            catch (Exception)
            {
                MessageBox.Show("Error sending email.", "ERROR", MessageBoxButton.OK);
            }

        }

        private void MeasurementListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                MonthViewModel selected = MeasurementListBox.SelectedItem as MonthViewModel;
                if (selected != null)
                {
                    var menuItemKey = selected.Key;
                    NavigationService.Navigate(new Uri("/DetailsPage.xaml?key=" + menuItemKey.ToString(), UriKind.Relative));
                }

            }
            catch (Exception)
            {
                MessageBox.Show("Error loading details page", "ERROR", MessageBoxButton.OK);
            }
        }

        private void btnEmail_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string email = txtEmail.Text.Trim();
                if (email != string.Empty)
                {
                    settings.EmailSettings = txtEmail.Text.Trim();
                }
                else
                {
                    MessageBox.Show("Write an email address.", "WARNING", MessageBoxButton.OK);
                }
            }
            catch (Exception)
            {
                
            }
        }

    }
}